﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CSF.Utility.Mvc;
using CSF.WebApp.Accounts.Models;
using CSF.Utility.Security;
using CSF.Service.Accounts.Client;
using CSF.Security.Data;
using System.ServiceModel;
using CSF.Customers.Data;
using CSF.BusinessCore.Service;

namespace CSF.WebApp.Accounts.Controllers
{
    public class AccountController : BaseController
    {


        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                string ipAddress = Request.UserHostAddress;
                string httpForwarded = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                AuthenticateSvcClient svc = new AuthenticateSvcClient();
                string sessionId = svc.LogOn(model.UserName, model.Password,
                    _application.Id, ipAddress, httpForwarded);
                if (sessionId != null)
                {
                    _toUrl = UrlUtility.AppendParameter(_toUrl, "SessionId", sessionId);
                    return Redirect(_toUrl);
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            return View(model);
        }

        public ActionResult Register()
        {
            RegisterViewData();
            return View();
        }

        [HttpPost]
        public ActionResult Register(Models.RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                UserAccount account = new UserAccount();
                account.UserName = model.Email;
                account.Email = model.Email;
                account.IsStaff = false;
                account.Password = model.Password;
                account.FirstName = model.FirstName;
                account.LastName = model.LastName;
                account.CreateBy = account.UserName;

                account.IsApproved = true;
                account.ApproveBy = account.UserName;
                account.ApproveTime = DateTime.Now;

                Customer customer = new Customer();
                customer.NickName = model.FirstName;
                customer.FullName = model.FirstName + " " + model.LastName;
                customer.Email = model.Email;
                customer.InMailList = model.InMailList;
                customer.CountryCode = model.CountryCode;
                customer.ApproveStatus = ApprovalStatus.Waiting;
                customer.CreateBy = account.UserName;

                try
                {
                    CustomerSvcClient svc = new CustomerSvcClient();
                    int id = svc.RegisterWithUser(account, customer, _application.Id);

                    AuthenticateSvcClient authsvc = new AuthenticateSvcClient();
                    string ipAddress = Request.UserHostAddress;
                    string httpForwarded = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                    string sessionId = authsvc.LogOn(account.UserName, account.Password, _application.Id, ipAddress, httpForwarded);
                    if (!string.IsNullOrEmpty(sessionId))
                    {
                        _toUrl = UrlUtility.AppendParameter(_toUrl, "SessionId=", sessionId);
                        return RedirectToAction("MyDetail", "Customer", new { SessionId = sessionId, toUrl = _toUrl });
                    }
                    else
                        return Redirect(_toUrl);
                }
                catch (FaultException<ExceptionWrapper<DuplicateUserNameException>>)
                {
                    ModelState.AddModelError("Email", "Email is registered by another user.");
                }
                catch (FaultException ex)
                {
                    ModelState.AddModelError("", ex);
                }
            }
            RegisterViewData();
            return View(model);
        }

        [NonAction]
        private void RegisterViewData()
        {
            CountrySvcClient countrySvc = new CountrySvcClient();
            var qcountry = from p in countrySvc.GetEnable()
                           orderby p.Name1
                           select new SelectListItem { Value = p.Code, Text = p.Name1 };
            ViewBag.CountryList = qcountry.AsEnumerable();
        }

        [Authorize]
        public ActionResult MyAccount()
        {
            UserAccountSvcClient svc = new UserAccountSvcClient();
            UserAccount userAccount = svc.GetOneById(_userSession.UserId);
            
            return View(userAccount);
        }

        [Authorize]
        [HttpPost]
        public ActionResult MyAccount(UserAccount userAccount)
        {
            if (ModelState.IsValid)
            {
                UserAccountSvcClient svc = new UserAccountSvcClient();

                svc.UpdateBySelf(userAccount);

                return Redirect(_toUrl);
            }
            return View(userAccount);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                UserAccountSvcClient svc = new UserAccountSvcClient();
                if (svc.ChangePassword(_userSession.UserId, model.OldPassword, model.NewPassword, User.Identity.Name))
                {
                    return Redirect(_toUrl);
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }
    }
}
